﻿using Microsoft.EntityFrameworkCore;
using YDT_ProductService.Domains.Interfaces;
using YDT_ProductService.Infrastructure.Datas;
using YDT_ProductService.Infrastructure.Repositorys;

namespace YDT_ProductService.Infrastructure
{
    /// <summary>
    /// 基础设施层依赖注入配置
    /// </summary>
    public static class DependencyInjection
    {
        /// <summary>
        /// 添加基础设施服务
        /// </summary>
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            // 获取数据库连接字符串
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidOperationException("数据库连接字符串 'DefaultConnection' 未配置");
            }

            // 注册数据库上下文
            services.AddDbContext<ProductServiceDbContext>(options =>
                options.UseMySql(connectionString, ServerVersion.Parse("5.7"),
                    mysqlOptions =>
                    {
                        // 配置MySQL选项
                        mysqlOptions.MigrationsAssembly(typeof(ProductServiceDbContext).Assembly.FullName);
                        // 可以添加其他MySQL特定配置
                        mysqlOptions.EnableRetryOnFailure(
                            maxRetryCount: 5,
                            maxRetryDelay: TimeSpan.FromSeconds(30),
                            errorNumbersToAdd: null);
                    }));

            // 注册仓储
            services.AddScoped<IProductRepository, ProductRepository>();

            return services;
        }
    }
}
